
module JConsole
    def JConsole.start(args={})
        port = args[:port] || 3000
        pwd_file = args[:pwd_file]
        access_file = args[:access_file]

        cmd =<<-EOCMD.split("\n").join(" ")
            jconsole
            -J-Dcom.sun.management.jmxremote 
            -J-Dcom.sun.management.jmxremote.port=#{port} 
            -J-Dcom.sun.management.jmxremote.ssl=false 
            -J-Dcom.sun.management.jmxremote.authenticate=#{!pwd_file.nil?}
        EOCMD
        if pwd_file
          cmd << " -J-Dcom.sun.management.jmxremote.password.file=#{pwd_file}" 
          cmd << " -J-Dcom.sun.management.jmxremote.access.file=#{access_file}"
        end 
        Thread.start { system cmd } 
        sleep 2
    end

    def JConsole.stop()
        jconsole_pid = `ps a -o pid,command | grep -w jconsole |  grep -v grep | grep -v ruby | cut -c -5`
        `kill #{jconsole_pid}` if jconsole_pid != ""
        sleep 2
    end
end

if ARGV.length == 1
    case ARGV[0]
    when "start"
        JConsole::start
        puts "started jconsole"
    when "stop"
        JConsole::stop
        puts "stopped jconsole"
    end
end
